<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>快速问答 - Telchina.AI</title>
    <link href="./assets/index.css" rel="stylesheet">
    <script src="./assets/plotly-latest.min.js" type="text/javascript"></script>
    <script src="./js/tailwind.min.js"></script>
    <script src="./assets/auth.js"></script>
    <script src="./assets/api-client.js"></script>
    <!-- Markdown解析库 -->
    <script src="https://cdn.jsdelivr.net/npm/marked@9.1.6/marked.min.js"></script>
    <!-- 代码高亮库 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github.min.css">
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/highlight.min.js"></script>
    <link rel="icon" type="image/svg+xml" href="./vanna.svg" />
</head>
<body class="bg-gray-50 dark:bg-gray-900">
    <div class="min-h-screen flex flex-col pt-16">
        <!-- 顶部导航 -->
        <nav class="fixed top-0 left-0 right-0 z-50 bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
            <div class="w-full px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between h-16">
                    <div class="flex items-center">
                        <img src="./telchina.svg" alt="Telchina.AI" class="h-8 w-8 mr-3">
                        <h1 class="text-xl font-semibold text-gray-900 dark:text-white">快速问答</h1>
                    </div>
                    <div class="flex items-center space-x-4">
                        <a href="index.html" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg font-medium flex items-center">
                            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
                            </svg>
                            返回首页
                        </a>
                        <a href="chat.html" class="text-gray-600 hover:text-gray-900 dark:text-gray-300 dark:hover:text-white px-3 py-2 rounded-md text-sm font-medium">AI对话</a>
                        <a href="training.html" class="text-gray-600 hover:text-gray-900 dark:text-gray-300 dark:hover:text-white px-3 py-2 rounded-md text-sm font-medium">训练SQL</a>
                        <a href="templates.html" class="text-gray-600 hover:text-gray-900 dark:text-gray-300 dark:hover:text-white px-3 py-2 rounded-md text-sm font-medium">SQL模板</a>
                        <button id="darkModeToggle" class="p-2 rounded-md text-gray-600 hover:text-gray-900 dark:text-gray-300 dark:hover:text-white">
                            <!-- 浅色模式图标 (全月) -->
                            <svg id="lightModeIcon" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path>
                            </svg>
                            <!-- 暗黑模式图标 (半月) -->
                            <svg id="darkModeIcon" class="w-5 h-5 hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 主要内容区域 -->
        <div class="flex-1 flex">
            <!-- 侧边栏 -->
            <div id="sidebar" class="w-64 bg-white dark:bg-gray-800 shadow-sm border-r border-gray-200 dark:border-gray-700 transition-all duration-300 ease-in-out relative group flex-shrink-0">
                <!-- 收起侧边栏按钮 -->
                <button id="sidebarToggle" class="absolute -right-3 top-1/2 -translate-y-1/2 z-10 w-6 h-6 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-full shadow-md text-gray-600 hover:text-gray-900 dark:text-gray-300 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center justify-center transition-all duration-300 opacity-0 group-hover:opacity-100">
                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                </button>
                <div class="p-4">
                    <button id="newQuestionBtn" class="w-full bg-gradient-to-r from-orange-600 to-amber-600 hover:from-orange-700 hover:to-amber-700 text-white font-semibold py-2.5 px-4 rounded-xl flex items-center justify-center space-x-2 shadow-md hover:shadow-lg transition-all duration-200 transform hover:scale-105 active:scale-95">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                        </svg>
                        <span>新问题</span>
                    </button>
                </div>
                <div class="px-4 pb-4">
                    <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">历史问答</h3>
                    <div id="qaHistory" class="space-y-1">
                        <!-- 历史问答列表 -->
                    </div>
                </div>
            </div>

            <!-- 问答区域 -->
            <div id="qaArea" class="flex-1 flex flex-col transition-all duration-300 ease-in-out relative">
                <!-- 展开侧边栏按钮（侧边栏收起时显示） -->
                <button id="sidebarExpandBtn" class="hidden fixed left-4 top-20 z-50 w-10 h-10 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-full shadow-lg text-gray-600 hover:text-gray-900 dark:text-gray-300 dark:hover:text-white hover:bg-gray-50 dark:hover:bg-gray-700 flex items-center justify-center transition-all duration-300 hover:scale-110">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
                    </svg>
                </button>
                <!-- 问答显示区域 -->
                <div id="qaContainer" class="flex-1 overflow-y-auto pb-24">
                    <div class="max-w-5xl mx-auto px-6">
                    <!-- 欢迎界面 -->
                    <div id="welcomeScreen" class="text-center text-gray-500 dark:text-gray-400 mt-20 animate-fade-in">
                        <div class="relative inline-block mb-8">
                            <div class="absolute inset-0 bg-gradient-to-r from-orange-400 to-amber-400 rounded-full blur-2xl opacity-30 animate-pulse"></div>
                            <svg class="w-24 h-24 mx-auto relative text-orange-500 dark:text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        <h2 class="text-3xl font-bold bg-gradient-to-r from-orange-600 to-amber-600 bg-clip-text text-transparent mb-4">快速问答助手</h2>
                        <p class="text-lg mb-3 text-gray-700 dark:text-gray-300">输入您的问题，AI将为您生成智能答案</p>
                        <p class="text-sm text-gray-500 dark:text-gray-400">支持自然语言查询，快速获得准确回答</p>
                        
                        <!-- 示例问题 -->
                        <div class="mt-10 max-w-2xl mx-auto">
                            <p class="text-sm font-medium text-gray-600 dark:text-gray-400 mb-4">试试这些问题：</p>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <div class="example-question bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-3 hover:border-orange-400 dark:hover:border-orange-500 hover:shadow-md transition-all duration-200 cursor-pointer text-left">
                                    <p class="text-sm text-gray-700 dark:text-gray-300">💡 如何提高工作效率？</p>
                                </div>
                                <div class="example-question bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-3 hover:border-orange-400 dark:hover:border-orange-500 hover:shadow-md transition-all duration-200 cursor-pointer text-left">
                                    <p class="text-sm text-gray-700 dark:text-gray-300">🚀 什么是人工智能？</p>
                                </div>
                                <div class="example-question bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-3 hover:border-orange-400 dark:hover:border-orange-500 hover:shadow-md transition-all duration-200 cursor-pointer text-left">
                                    <p class="text-sm text-gray-700 dark:text-gray-300">📊 如何分析数据？</p>
                                </div>
                                <div class="example-question bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-3 hover:border-orange-400 dark:hover:border-orange-500 hover:shadow-md transition-all duration-200 cursor-pointer text-left">
                                    <p class="text-sm text-gray-700 dark:text-gray-300">🎯 如何设定目标？</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 问答内容区域 -->
                    <div id="qaContent" class="hidden max-w-4xl mx-auto">
                        <!-- 连续对话记录 -->
                        <div id="conversationHistory" class="space-y-6 mb-6">
                            <!-- 对话记录将在这里动态添加 -->
                        </div>


                    </div>

                    <!-- 加载状态 -->
                    <div id="loadingState" class="hidden text-center py-12">
                        <div class="inline-flex items-center space-x-3 bg-gradient-to-r from-orange-50 to-amber-50 dark:from-orange-900/20 dark:to-amber-900/20 px-6 py-4 rounded-2xl shadow-lg">
                            <div class="relative">
                                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-orange-600"></div>
                                <div class="absolute inset-0 animate-ping rounded-full h-8 w-8 border border-orange-400 opacity-20"></div>
                            </div>
                            <span class="text-lg font-medium text-gray-700 dark:text-gray-300">AI正在思考中...</span>
                        </div>
                    </div>
                    </div>
                </div>

                <!-- 输入区域 -->
                <div id="inputArea" class="fixed bottom-0 left-0 right-0 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 p-3 z-40" style="margin-left: 256px; transition: margin-left 300ms ease-in-out;">
                    <div class="max-w-4xl mx-auto">
                        <!-- 新问题按钮区域 -->
                        <div class="mb-2 flex justify-start">
                            <button id="newQuestionBtn2" class="group bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white px-3 py-1.5 rounded-full text-sm font-medium flex items-center space-x-2 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105 active:scale-95">
                                <svg class="w-4 h-4 transition-transform group-hover:rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                                <span class="font-semibold">新问题</span>
                            </button>
                        </div>
                        
                        <!-- 输入框和提问按钮 -->
                        <div class="flex space-x-3">
                            <div class="flex-1">
                                <textarea id="questionInput" 
                                        placeholder="请输入您的问题..." 
                                        class="w-full p-2.5 border-2 border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 dark:bg-gray-800 dark:text-white resize-none transition-all duration-200 shadow-sm focus:shadow-md"
                                        rows="1"></textarea>
                            </div>
                            <button id="askBtn" 
                                    class="bg-gradient-to-r from-orange-600 to-amber-600 hover:from-orange-700 hover:to-amber-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-2 px-5 rounded-lg transition-all duration-200 flex items-center space-x-2 shadow-lg hover:shadow-xl transform hover:scale-105 active:scale-95 disabled:transform-none disabled:cursor-not-allowed">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                                </svg>
                                <span>提问</span>
                            </button>
                        </div>
                        
                        <!-- 提示文字 -->
                        <div class="mt-1.5 text-xs text-gray-500 dark:text-gray-400 text-center">
                            按 Enter 发送，Shift + Enter 换行
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 更新图标显示
        function updateThemeIcon(isDark) {
            const lightIcon = document.getElementById('lightModeIcon');
            const darkIcon = document.getElementById('darkModeIcon');
            
            if (isDark) {
                // 暗黑模式：显示半月图标
                lightIcon.classList.add('hidden');
                darkIcon.classList.remove('hidden');
            } else {
                // 浅色模式：显示全月图标
                lightIcon.classList.remove('hidden');
                darkIcon.classList.add('hidden');
            }
        }

        // 初始化暗色模式
        const isDarkMode = localStorage.getItem('darkMode') === 'true';
        if (isDarkMode) {
            document.documentElement.classList.add('dark');
        }

        document.addEventListener('DOMContentLoaded', function() {
            // 初始化图标状态
            updateThemeIcon(isDarkMode);
            // DOM 元素
            const darkModeToggle = document.getElementById('darkModeToggle');
            const sidebarToggle = document.getElementById('sidebarToggle');
            const sidebar = document.getElementById('sidebar');
            const qaArea = document.getElementById('qaArea');
            const questionInput = document.getElementById('questionInput');
            const askBtn = document.getElementById('askBtn');
            const newQuestionBtn = document.getElementById('newQuestionBtn');
            const newQuestionBtn2 = document.getElementById('newQuestionBtn2');

            const welcomeScreen = document.getElementById('welcomeScreen');
            const qaContent = document.getElementById('qaContent');
            const loadingState = document.getElementById('loadingState');
            const conversationHistory = document.getElementById('conversationHistory');
            const qaHistory = document.getElementById('qaHistory');

            let currentQuestionId = null;
            let qaHistoryData = JSON.parse(localStorage.getItem('qaHistory') || '[]');
            let currentConversation = []; // 当前会话的对话记录
            let showAllConversations = false; // 是否显示所有对话记录
            const MAX_VISIBLE_CONVERSATIONS = 5; // 最大显示对话数量

            // 内容格式检测和渲染功能
            const ContentRenderer = {
                // 错误日志记录
                logError: function(operation, error, content) {
                    const errorInfo = {
                        timestamp: new Date().toISOString(),
                        operation: operation,
                        error: error.message || error,
                        contentLength: content ? content.length : 0,
                        contentPreview: content ? content.substring(0, 100) : '',
                        userAgent: navigator.userAgent
                    };
                    
                    console.error(`ContentRenderer ${operation} 失败:`, errorInfo);
                    
                    // 保存错误日志到localStorage（可选）
                    try {
                        const errorLogs = JSON.parse(localStorage.getItem('contentRenderErrors') || '[]');
                        errorLogs.push(errorInfo);
                        // 只保留最近50条错误记录
                        if (errorLogs.length > 50) {
                            errorLogs.splice(0, errorLogs.length - 50);
                        }
                        localStorage.setItem('contentRenderErrors', JSON.stringify(errorLogs));
                    } catch (logError) {
                        console.warn('无法保存错误日志:', logError);
                    }
                },

                // 检测内容是否为Markdown格式
                isMarkdown: function(content) {
                    if (!content || typeof content !== 'string') {
                        return false;
                    }
                    
                    try {
                        // Markdown特征检测
                        const markdownPatterns = [
                            /^#{1,6}\s+/m,           // 标题 (# ## ### 等)
                            /\*\*.*?\*\*/,           // 粗体 **text**
                            /\*.*?\*/,               // 斜体 *text*
                            /`.*?`/,                 // 行内代码 `code`
                            /```[\s\S]*?```/,        // 代码块 ```code```
                            /^\s*[-*+]\s+/m,         // 无序列表
                            /^\s*\d+\.\s+/m,         // 有序列表
                            /\[.*?\]\(.*?\)/,        // 链接 [text](url)
                            /!\[.*?\]\(.*?\)/,       // 图片 ![alt](url)
                            /^\s*>\s+/m,             // 引用 > text
                            /^\s*\|.*\|.*\|/m,       // 表格
                            /^---+$/m,               // 分隔线
                            /~~.*?~~/,               // 删除线 ~~text~~
                        ];
                        
                        // 计算匹配的模式数量
                        let matchCount = 0;
                        for (const pattern of markdownPatterns) {
                            if (pattern.test(content)) {
                                matchCount++;
                            }
                        }
                        
                        // 如果匹配多个模式，或者内容较长且匹配至少一个模式，则认为是Markdown
                        return matchCount >= 2 || (content.length > 100 && matchCount >= 1);
                    } catch (error) {
                        this.logError('格式检测', error, content);
                        return false; // 检测失败时默认为普通文本
                    }
                },

                // 渲染Markdown内容
                renderMarkdown: function(content) {
                    try {
                        // 配置marked选项
                        marked.setOptions({
                            highlight: function(code, lang) {
                                if (lang && hljs.getLanguage(lang)) {
                                    try {
                                        return hljs.highlight(code, { language: lang }).value;
                                    } catch (err) {
                                        console.warn('代码高亮失败:', err);
                                    }
                                }
                                return hljs.highlightAuto(code).value;
                            },
                            breaks: true,
                            gfm: true
                        });
                        
                        const rendered = marked.parse(content);
                        console.log('Markdown渲染成功');
                        return rendered;
                    } catch (error) {
                        this.logError('Markdown渲染', error, content);
                        // 渲染失败时返回转义后的HTML
                        return this.renderPlainText(content);
                    }
                },

                // 渲染普通文本内容
                renderPlainText: function(content) {
                    try {
                        // HTML转义
                        const escaped = content
                            .replace(/&/g, '&amp;')
                            .replace(/</g, '&lt;')
                            .replace(/>/g, '&gt;')
                            .replace(/"/g, '&quot;')
                            .replace(/'/g, '&#39;');
                        
                        // 保持换行
                        const withBreaks = escaped.replace(/\n/g, '<br>');
                        
                        console.log('普通文本渲染成功');
                        return withBreaks;
                    } catch (error) {
                        this.logError('普通文本渲染', error, content);
                        return content; // 失败时返回原内容
                    }
                },

                // 智能渲染内容
                render: function(content) {
                    if (!content) {
                        return '';
                    }
                    
                    try {
                        if (this.isMarkdown(content)) {
                            console.log('检测到Markdown格式，使用Markdown渲染');
                            return this.renderMarkdown(content);
                        } else {
                            console.log('检测到普通文本格式，使用文本渲染');
                            return this.renderPlainText(content);
                        }
                    } catch (error) {
                        this.logError('智能渲染', error, content);
                        // 错误处理：返回基本的HTML转义内容
                        return this.renderPlainText(content);
                    }
                },

                // 获取错误日志（用于调试）
                getErrorLogs: function() {
                    try {
                        return JSON.parse(localStorage.getItem('contentRenderErrors') || '[]');
                    } catch (error) {
                        console.warn('无法获取错误日志:', error);
                        return [];
                    }
                },

                // 清除错误日志
                clearErrorLogs: function() {
                    try {
                        localStorage.removeItem('contentRenderErrors');
                        console.log('错误日志已清除');
                    } catch (error) {
                        console.warn('无法清除错误日志:', error);
                    }
                }
            };

            // 暗色模式切换
            if (darkModeToggle) {
                darkModeToggle.addEventListener('click', function() {
                    const isDark = document.documentElement.classList.toggle('dark');
                    localStorage.setItem('darkMode', isDark.toString());
                    updateThemeIcon(isDark);
                });
            }

            // 侧边栏切换
            const sidebarExpandBtn = document.getElementById('sidebarExpandBtn');
            
            function toggleSidebar(show) {
                const inputArea = document.getElementById('inputArea');
                
                if (show) {
                    // 显示侧边栏
                    sidebar.style.width = '256px';
                    sidebar.style.overflow = 'visible';
                    if (inputArea) {
                        inputArea.style.marginLeft = '256px';
                    }
                    if (sidebarExpandBtn) {
                        sidebarExpandBtn.classList.add('hidden');
                    }
                    // 更新按钮图标
                    sidebarToggle.querySelector('svg path').setAttribute('d', 'M15 19l-7-7 7-7');
                } else {
                    // 隐藏侧边栏
                    sidebar.style.width = '0px';
                    sidebar.style.overflow = 'hidden';
                    if (inputArea) {
                        inputArea.style.marginLeft = '0px';
                    }
                    if (sidebarExpandBtn) {
                        sidebarExpandBtn.classList.remove('hidden');
                    }
                    // 更新按钮图标
                    sidebarToggle.querySelector('svg path').setAttribute('d', 'M9 5l7 7-7 7');
                }
            }
            
            if (sidebarToggle) {
                sidebarToggle.addEventListener('click', function() {
                    const isClosed = sidebar.style.width === '0px';
                    toggleSidebar(isClosed);
                });
            }
            
            if (sidebarExpandBtn) {
                sidebarExpandBtn.addEventListener('click', function() {
                    toggleSidebar(true);
                });
            }

            // 新问题按钮
            function resetToWelcome() {
                welcomeScreen.classList.remove('hidden');
                qaContent.classList.add('hidden');
                loadingState.classList.add('hidden');
                questionInput.value = '';
                currentQuestionId = null;
                currentConversation = [];
                conversationHistory.innerHTML = '';
                showAllConversations = false;
            }

            if (newQuestionBtn) {
                newQuestionBtn.addEventListener('click', resetToWelcome);
            }
            if (newQuestionBtn2) {
                newQuestionBtn2.addEventListener('click', resetToWelcome);
            }



            // 渲染对话记录
            function renderConversation() {
                conversationHistory.innerHTML = '';
                
                // 确定要显示的对话记录
                const conversationsToShow = showAllConversations ? 
                    currentConversation : 
                    currentConversation.slice(-MAX_VISIBLE_CONVERSATIONS);
                
                // 如果有隐藏的对话记录，显示展开按钮
                if (!showAllConversations && currentConversation.length > MAX_VISIBLE_CONVERSATIONS) {
                    const expandButton = document.createElement('div');
                    expandButton.className = 'text-center mb-4';
                    expandButton.innerHTML = `
                        <button id="expandConversations" class="bg-gradient-to-r from-gray-100 to-gray-200 hover:from-gray-200 hover:to-gray-300 dark:from-gray-700 dark:to-gray-600 dark:hover:from-gray-600 dark:hover:to-gray-500 text-gray-700 dark:text-gray-200 px-5 py-2.5 rounded-xl text-sm font-medium flex items-center space-x-2 mx-auto shadow-sm hover:shadow-md transition-all duration-200">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7-7-7 7"></path>
                            </svg>
                            <span>显示更早的 ${currentConversation.length - MAX_VISIBLE_CONVERSATIONS} 轮对话</span>
                        </button>
                    `;
                    conversationHistory.appendChild(expandButton);
                }
                
                conversationsToShow.forEach((item, index) => {
                    const actualIndex = showAllConversations ? index : (currentConversation.length - conversationsToShow.length + index);
                    const qaItem = document.createElement('div');
                    qaItem.className = 'space-y-4';
                    qaItem.innerHTML = `
                        <!-- 问题显示 -->
                        <div class="bg-gradient-to-r from-indigo-50 via-purple-50 to-pink-50 dark:from-indigo-900/30 dark:via-purple-900/30 dark:to-pink-900/30 border border-indigo-200 dark:border-indigo-700 rounded-xl p-5 shadow-sm hover:shadow-md transition-shadow duration-200">
                            <div class="flex items-start space-x-3">
                                <div class="flex-shrink-0">
                                    <div class="w-10 h-10 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full flex items-center justify-center shadow-lg">
                                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                        </svg>
                                    </div>
                                </div>
                                <div class="flex-1">
                                    <div class="flex items-center justify-between mb-2">
                                        <h3 class="text-sm font-semibold text-indigo-900 dark:text-indigo-100">您的问题 ${actualIndex + 1}</h3>
                                        <span class="text-xs text-indigo-600 dark:text-indigo-400 bg-indigo-100 dark:bg-indigo-900/50 px-2 py-1 rounded-full">${item.questionTime ? new Date(item.questionTime).toLocaleString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}) : ''}</span>
                                    </div>
                                    <p class="text-gray-800 dark:text-gray-200 leading-relaxed">${item.question}</p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 答案显示 -->
                        <div class="bg-gradient-to-r from-emerald-50 via-teal-50 to-cyan-50 dark:from-emerald-900/30 dark:via-teal-900/30 dark:to-cyan-900/30 border border-emerald-200 dark:border-emerald-700 rounded-xl p-5 shadow-sm hover:shadow-md transition-shadow duration-200">
                            <div class="flex items-start space-x-3">
                                <div class="flex-shrink-0">
                                    <div class="w-10 h-10 bg-gradient-to-br from-emerald-500 to-teal-600 rounded-full flex items-center justify-center shadow-lg">
                                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                        </svg>
                                    </div>
                                </div>
                                <div class="flex-1">
                                    <div class="flex items-center justify-between mb-2">
                                        <div class="flex items-center space-x-2">
                                            <h3 class="text-sm font-semibold text-emerald-900 dark:text-emerald-100">AI 答案 ${actualIndex + 1}</h3>
                                            <span class="text-xs text-emerald-600 dark:text-emerald-400 bg-emerald-100 dark:bg-emerald-900/50 px-2 py-1 rounded-full">${item.answerTime ? new Date(item.answerTime).toLocaleString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}) : ''}</span>
                                        </div>
                                        <button class="copy-answer-btn bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 text-white px-3 py-1.5 rounded-lg text-xs font-medium flex items-center space-x-1 transition-all duration-200 shadow-sm hover:shadow-md" data-answer="${item.answer.replace(/"/g, '&quot;')}">
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
                                            </svg>
                                            <span>复制</span>
                                        </button>
                                    </div>
                                    ${item.isLoading && item.status ? 
`<div class="flex items-center space-x-2 text-emerald-600 dark:text-emerald-400 mb-2 status-message">
<div class="animate-spin rounded-full h-4 w-4 border-b-2 border-emerald-600"></div>
<span>${item.status}</span>
</div>` : ''}
                                    <div class="text-gray-800 dark:text-gray-200 answer-content leading-relaxed" data-full-answer="${item.answer.replace(/"/g, '&quot;')}">
${item.isLoading && !item.answer ? 
'<div class="flex items-center space-x-2 text-emerald-600 dark:text-emerald-400"><div class="animate-spin rounded-full h-4 w-4 border-b-2 border-emerald-600"></div><span>AI正在思考中...</span></div>' : 
(item.answer.length > 500 ? 
`<div class="answer-preview">${ContentRenderer.render(item.answer.substring(0, 500))}...</div>
<button class="expand-answer-btn text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 dark:hover:text-emerald-300 text-sm font-medium mt-2 flex items-center space-x-1">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7-7-7 7"></path>
</svg>
<span>展开完整答案</span>
</button>` : 
ContentRenderer.render(item.answer))
}
                                    </div>
                                    <div class="mt-3 text-xs text-emerald-600 dark:text-emerald-400 bg-emerald-100 dark:bg-emerald-900/50 px-2 py-1 rounded inline-block">问答ID: ${item.id}</div>
                                </div>
                            </div>
                        </div>
                    `;
                    conversationHistory.appendChild(qaItem);
                });
                
                // 为每个复制按钮添加事件监听器
                const copyButtons = conversationHistory.querySelectorAll('.copy-answer-btn');
                copyButtons.forEach(button => {
                    button.addEventListener('click', function() {
                        const answer = this.getAttribute('data-answer').replace(/&quot;/g, '"');
                        navigator.clipboard.writeText(answer).then(() => {
                            // 临时改变按钮文本
                            const originalHTML = this.innerHTML;
                            this.innerHTML = `
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                                </svg>
                                <span>已复制</span>
                            `;
                            this.classList.remove('bg-green-600', 'hover:bg-green-700');
                            this.classList.add('bg-green-700');
                            
                            setTimeout(() => {
                                this.innerHTML = originalHTML;
                                this.classList.remove('bg-green-700');
                                this.classList.add('bg-green-600', 'hover:bg-green-700');
                            }, 2000);
                        }).catch(err => {
                            console.error('复制失败:', err);
                            alert('复制失败，请手动复制');
                        });
                    });
                });
                
                // 为每个展开答案按钮添加事件监听器
                const expandAnswerButtons = conversationHistory.querySelectorAll('.expand-answer-btn');
                expandAnswerButtons.forEach(button => {
                    button.addEventListener('click', function() {
                        const answerContent = this.closest('.answer-content');
                        const fullAnswer = answerContent.getAttribute('data-full-answer').replace(/&quot;/g, '"');
                        const isExpanded = answerContent.classList.contains('expanded');
                        
                        if (isExpanded) {
                            // 收起答案
                            answerContent.innerHTML = `<div class="answer-preview">${ContentRenderer.render(fullAnswer.substring(0, 500))}...</div>
<button class="expand-answer-btn text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 dark:hover:text-emerald-300 text-sm font-medium mt-2 flex items-center space-x-1">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7-7-7 7"></path>
</svg>
<span>展开完整答案</span>
</button>`;
                            answerContent.classList.remove('expanded');
                        } else {
                            // 展开答案
                            answerContent.innerHTML = `${ContentRenderer.render(fullAnswer)}
<button class="expand-answer-btn text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 dark:hover:text-emerald-300 text-sm font-medium mt-2 flex items-center space-x-1">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7 7 7-7"></path>
</svg>
<span>收起答案</span>
</button>`;
                            answerContent.classList.add('expanded');
                        }
                        
                        // 重新为新创建的按钮绑定事件监听器
                        const newExpandButton = answerContent.querySelector('.expand-answer-btn');
                        if (newExpandButton) {
                            newExpandButton.addEventListener('click', arguments.callee);
                        }
                    });
                });
                
                // 添加展开按钮事件监听器
                const expandBtn = document.getElementById('expandConversations');
                if (expandBtn) {
                    expandBtn.addEventListener('click', function() {
                        showAllConversations = true;
                        renderConversation();
                    });
                }
                
                // 如果显示所有对话且对话数量超过限制，添加收起按钮
                if (showAllConversations && currentConversation.length > MAX_VISIBLE_CONVERSATIONS) {
                    const collapseButton = document.createElement('div');
                    collapseButton.className = 'text-center mt-4';
                    collapseButton.innerHTML = `
                        <button id="collapseConversations" class="bg-gradient-to-r from-gray-100 to-gray-200 hover:from-gray-200 hover:to-gray-300 dark:from-gray-700 dark:to-gray-600 dark:hover:from-gray-600 dark:hover:to-gray-500 text-gray-700 dark:text-gray-200 px-5 py-2.5 rounded-xl text-sm font-medium flex items-center space-x-2 mx-auto shadow-sm hover:shadow-md transition-all duration-200">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7 7 7-7"></path>
                            </svg>
                            <span>收起较早对话</span>
                        </button>
                    `;
                    conversationHistory.appendChild(collapseButton);
                    
                    const collapseBtn = document.getElementById('collapseConversations');
                    if (collapseBtn) {
                        collapseBtn.addEventListener('click', function() {
                            showAllConversations = false;
                            renderConversation();
                        });
                    }
                }
                
                // 滚动到底部
                setTimeout(() => {
                    conversationHistory.scrollIntoView({ behavior: 'smooth', block: 'end' });
                }, 100);
            }

            // 提问功能
            async function askQuestion() {
                const question = questionInput.value.trim();
                if (!question) {
                    alert('请输入问题');
                    return;
                }

                // 记录问题发送时间
                const questionTime = new Date().toISOString();

                // 立即显示问题在面板上
                const tempQaItem = {
                    id: 'pending',
                    question: question,
                    answer: '',
                    questionTime: questionTime,
                    answerTime: null,
                    timestamp: questionTime,
                    isLoading: true
                };
                currentConversation.push(tempQaItem);

                // 清空输入框
                questionInput.value = '';

                // 显示问答内容区域
                welcomeScreen.classList.add('hidden');
                loadingState.classList.add('hidden');
                qaContent.classList.remove('hidden');

                // 渲染对话记录（显示问题和加载状态）
                renderConversation();

                try {
                    // 禁用提问按钮
                    askBtn.disabled = true;

                    let apiUrl = `/api/v0/generate_answer?question=${encodeURIComponent(question)}&stream=false`;
                    if (currentQuestionId) {
                        apiUrl += `&id=${encodeURIComponent(currentQuestionId)}`;
                    }

                    // 使用 fetch 进行非流式调用
                    fetch(apiUrl)
                        .then(response => response.json())
                        .then(data => {
                            // 更新会话ID
                            currentQuestionId = data.id;
                            
                            // 更新对话记录
                            const answerTime = new Date().toISOString();
                            currentConversation[currentConversation.length - 1] = {
                                id: data.id,
                                question: question,
                                answer: data.message || '暂无答案',
                                questionTime: questionTime,
                                answerTime: answerTime,
                                timestamp: answerTime,
                                isLoading: false,
                                type: data.type
                            };

                            // 保存到历史记录
                            qaHistoryData.unshift(currentConversation[currentConversation.length - 1]);
                            if (qaHistoryData.length > 50) qaHistoryData.pop();
                            localStorage.setItem('qaHistory', JSON.stringify(qaHistoryData));
                            updateHistoryDisplay();

                            // 渲染对话记录
                            renderConversation();
                            askBtn.disabled = false;
                        })
                        .catch(error => {
                            console.error('Error asking question:', error);
                            
                            // 更新最后一条记录为错误信息
                            currentConversation[currentConversation.length - 1] = {
                                id: 'error',
                                question: question,
                                answer: `❌ 错误: ${error.message}`,
                                questionTime: questionTime,
                                answerTime: new Date().toISOString(),
                                timestamp: new Date().toISOString(),
                                isLoading: false
                            };
                            
                            // 渲染对话记录
                            renderConversation();
                            askBtn.disabled = false;
                        });
                    
                    return; // 提前返回，不执行下面的 EventSource 代码
                    
                    // 下面的代码不会执行（保留用于流式版本）
                    const eventSource = new EventSource(apiUrl);
                    let fullAnswer = '';
                    let sessionId = null;
                    let answerType = 'other';
                    let statusMessage = '';

                    // 获取当前答案容器的引用（避免每次都重新渲染）
                    let currentAnswerElement = null;
                    
                    eventSource.onmessage = (event) => {
                        try {
                            const data = JSON.parse(event.data);
                            
                            // 更新会话ID和类型
                            if (data.id) {
                                sessionId = data.id;
                                currentQuestionId = data.id;
                            }
                            if (data.type) {
                                answerType = data.type;
                            }

                            switch(data.event) {
                                case 'status':
                                    // 更新状态消息
                                    statusMessage = data.message;
                                    currentConversation[currentConversation.length - 1] = {
                                        id: sessionId || 'loading',
                                        question: question,
                                        answer: fullAnswer || statusMessage,
                                        questionTime: questionTime,
                                        answerTime: new Date().toISOString(),
                                        timestamp: new Date().toISOString(),
                                        isLoading: true,
                                        status: statusMessage
                                    };
                                    
                                    // 只在第一次或状态变化时重新渲染
                                    if (!currentAnswerElement) {
                                        renderConversation();
                                        // 获取最后一个答案元素的引用
                                        const answerElements = conversationHistory.querySelectorAll('.answer-content');
                                        currentAnswerElement = answerElements[answerElements.length - 1];
                                    } else {
                                        // 只更新状态文本
                                        const statusElement = currentAnswerElement.querySelector('.status-message');
                                        if (statusElement) {
                                            statusElement.textContent = statusMessage;
                                        }
                                    }
                                    break;
                                    
                                case 'stream':
                                    // 累积流式内容
                                    fullAnswer += data.delta;
                                    currentConversation[currentConversation.length - 1] = {
                                        id: sessionId || 'loading',
                                        question: question,
                                        answer: fullAnswer,
                                        questionTime: questionTime,
                                        answerTime: new Date().toISOString(),
                                        timestamp: new Date().toISOString(),
                                        isLoading: true,
                                        type: answerType
                                    };
                                    
                                    // 只更新答案内容，不重新渲染整个页面
                                    if (!currentAnswerElement) {
                                        renderConversation();
                                        const answerElements = conversationHistory.querySelectorAll('.answer-content');
                                        currentAnswerElement = answerElements[answerElements.length - 1];
                                    }
                                    
                                    if (currentAnswerElement) {
                                        // 直接更新答案内容
                                        currentAnswerElement.innerHTML = ContentRenderer.render(fullAnswer);
                                    }
                                    break;
                                    
                                case 'complete':
                                    // 完成
                                    const answerTime = new Date().toISOString();
                                    currentConversation[currentConversation.length - 1] = {
                                        id: data.id,
                                        question: question,
                                        answer: data.message || fullAnswer || '暂无答案',
                                        questionTime: questionTime,
                                        answerTime: answerTime,
                                        timestamp: answerTime,
                                        isLoading: false,
                                        type: data.type
                                    };
                                    currentQuestionId = data.id;

                                    // 保存到历史记录
                                    qaHistoryData.unshift(currentConversation[currentConversation.length - 1]);
                                    if (qaHistoryData.length > 50) qaHistoryData.pop();
                                    localStorage.setItem('qaHistory', JSON.stringify(qaHistoryData));
                                    updateHistoryDisplay();

                                    // 最后重新渲染一次，确保格式正确
                                    renderConversation();
                                    currentAnswerElement = null;
                                    
                                    // 关闭连接
                                    eventSource.close();
                                    askBtn.disabled = false;
                                    break;
                                    
                                case 'error':
                                    // 错误处理
                                    throw new Error(data.error || '生成答案时发生错误');
                            }
                        } catch (parseError) {
                            console.error('解析事件数据失败:', parseError);
                        }
                    };

                    eventSource.onerror = (error) => {
                        console.error('EventSource 错误:', error);
                        eventSource.close();
                        
                        // 更新最后一条记录为错误信息
                        currentConversation[currentConversation.length - 1] = {
                            id: sessionId || 'error',
                            question: question,
                            answer: fullAnswer || `❌ 连接错误，请重试`,
                            questionTime: questionTime,
                            answerTime: new Date().toISOString(),
                            timestamp: new Date().toISOString(),
                            isLoading: false
                        };
                        
                        renderConversation();
                        askBtn.disabled = false;
                    };

                } catch (error) {
                    console.error('Error asking question:', error);
                    
                    // 更新最后一条记录为错误信息
                    currentConversation[currentConversation.length - 1] = {
                        id: 'error',
                        question: question,
                        answer: `❌ 错误: ${error.message}`,
                        questionTime: questionTime,
                        answerTime: new Date().toISOString(),
                        timestamp: new Date().toISOString(),
                        isLoading: false
                    };
                    
                    // 渲染对话记录
                    renderConversation();
                    askBtn.disabled = false;
                }
            }

            // 按钮点击事件
            if (askBtn) {
                askBtn.addEventListener('click', askQuestion);
            }

            // 回车键事件
            if (questionInput) {
                questionInput.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        askQuestion();
                    }
                });
            }

            // 更新历史记录显示
            function updateHistoryDisplay() {
                qaHistory.innerHTML = '';
                qaHistoryData.slice(0, 10).forEach(item => {
                    const historyItem = document.createElement('div');
                    historyItem.className = 'p-3 rounded-lg hover:bg-gradient-to-r hover:from-orange-50 hover:to-amber-50 dark:hover:from-orange-900/20 dark:hover:to-amber-900/20 cursor-pointer text-sm border border-transparent hover:border-orange-200 dark:hover:border-orange-700 transition-all duration-200';
                    historyItem.innerHTML = `
                        <div class="font-medium text-gray-900 dark:text-white truncate">${item.question}</div>
                        <div class="text-xs text-gray-500 dark:text-gray-400 mt-1.5 flex items-center space-x-1">
                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            <span>${new Date(item.timestamp).toLocaleString()}</span>
                        </div>
                    `;
                    historyItem.addEventListener('click', () => {
                        // 将单个历史记录作为新会话显示
                        currentConversation = [{
                            id: item.id,
                            question: item.question,
                            answer: item.answer,
                            questionTime: item.questionTime || item.timestamp, // 兼容旧数据
                            answerTime: item.answerTime || item.timestamp, // 兼容旧数据
                            timestamp: item.timestamp
                        }];
                        currentQuestionId = item.id;
                        
                        // 渲染对话记录
                        renderConversation();
                        
                        welcomeScreen.classList.add('hidden');
                        loadingState.classList.add('hidden');
                        qaContent.classList.remove('hidden');
                    });
                    qaHistory.appendChild(historyItem);
                });
            }

            // 初始化历史记录
            updateHistoryDisplay();

            // 示例问题点击事件
            document.querySelectorAll('.example-question').forEach(exampleBtn => {
                exampleBtn.addEventListener('click', function() {
                    const questionText = this.querySelector('p').textContent.trim();
                    // 移除emoji和空格
                    const cleanQuestion = questionText.replace(/^[^\w\s]+\s*/, '');
                    questionInput.value = cleanQuestion;
                    questionInput.focus();
                    // 添加点击动画
                    this.classList.add('scale-95');
                    setTimeout(() => {
                        this.classList.remove('scale-95');
                    }, 150);
                });
            });
        });
    </script>
    
    <style>
        /* 添加淡入动画 */
        @keyframes fade-in {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .animate-fade-in {
            animation: fade-in 0.6s ease-out;
        }
        
        /* 问答项淡入动画 */
        #conversationHistory > div {
            animation: fade-in 0.4s ease-out;
        }
        
        /* 平滑滚动 */
        #qaContainer {
            scroll-behavior: smooth;
        }
        
        /* 代码块样式优化 */
        .answer-content pre {
            background: #f6f8fa;
            border-radius: 8px;
            padding: 16px;
            overflow-x: auto;
            margin: 12px 0;
        }
        
        .dark .answer-content pre {
            background: #1f2937;
        }
        
        .answer-content code {
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
        }
        
        .answer-content p {
            margin: 8px 0;
            line-height: 1.6;
        }
        
        .answer-content ul, .answer-content ol {
            margin: 8px 0;
            padding-left: 24px;
        }
        
        .answer-content li {
            margin: 4px 0;
        }
        
        .answer-content h1, .answer-content h2, .answer-content h3 {
            margin: 16px 0 8px 0;
            font-weight: 600;
        }
        
        .answer-content blockquote {
            border-left: 4px solid #10b981;
            padding-left: 16px;
            margin: 12px 0;
            color: #6b7280;
        }
        
        .dark .answer-content blockquote {
            border-left-color: #059669;
            color: #9ca3af;
        }
        
        /* 输入框聚焦效果 */
        #questionInput:focus {
            outline: none;
        }
        
        /* 按钮禁用状态 */
        #askBtn:disabled {
            opacity: 0.6;
        }
        
        /* 示例问题缩放动画 */
        .example-question {
            transition: all 0.2s ease;
        }
        
        .example-question.scale-95 {
            transform: scale(0.95);
        }
    </style>
</body>
</html>